package csm.web.core.search.mashup.aladin;

import java.io.IOException;
import java.util.List;

import org.jdom.Element;
import org.jdom.JDOMException;

import csm.common.StringUtil;
import csm.common.xml.XmlDocument;
import csm.web.core.search.BriefItem;
import csm.web.core.search.SearchResultInfo;

public class AladinSearchResult  extends SearchResultInfo{

	@Override
	public void parseResult(String responseString) {
		int hitcount = 0;
		int pageSize = 10;
		int page = 1;
		BriefItem item;


		if(StringUtil.isNullOrEmpty(responseString)) return;
		setResultString(responseString);

		XmlDocument xmlDoc = null;

		responseString.replaceAll("&\\#x[0-9][A-F]?;", " ");

		try {
			xmlDoc = new XmlDocument(responseString);

			Element element = (Element)xmlDoc.selectSingleNode("//rss/channel");
			hitcount = Integer.parseInt(  element.getChildText("totalResults", xmlDoc.getNamespaces("opensearch")) );

			setHitCount(hitcount);

			List<?> list = xmlDoc.selectNodes("//rss/channel/item");
			for (int i = 0 ; i < list.size(); i++) {
				Element el = (Element)list.get(i);
				item = new BriefItem();
				item.add("title", el.getChildText("title"));
				item.setTitle(el.getChildText("title"));

				item.add("author", el.getChildText("author"));
				item.setAuthor(el.getChildText("author"));

				item.add("publisher", el.getChildText("publisher",  xmlDoc.getNamespaces("aladdin")));
				item.setPublisher(el.getChildText("publisher", xmlDoc.getNamespaces("aladdin")));

				item.add("date", el.getChildText("date", xmlDoc.getNamespaces("dc")));
				item.setPubYear(el.getChildText("date", xmlDoc.getNamespaces("dc")));

				item.add("cover", el.getChildText("cover", xmlDoc.getNamespaces("aladdin")));
				item.setThumbNailUrl(el.getChildText("cover", xmlDoc.getNamespaces("aladdin")));

				item.add("isbn", el.getChildText("isbn", xmlDoc.getNamespaces("aladdin")));
				item.setIsbn(el.getChildText("isbn", xmlDoc.getNamespaces("aladdin")));

				item.add("link", el.getChildText("link"));
				item.setLink(el.getChildText("link"));

				item.add("priceStandard", el.getChildText("priceStandard", xmlDoc.getNamespaces("aladdin")));
				item.setPrice(el.getChildText("priceStandard", xmlDoc.getNamespaces("aladdin")));

				item.add("description", el.getChildText("description"));
				item.setDescription(el.getChildText("description"));

				this.addBriefItem(item);
			}

		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
